﻿using System;
using System.Drawing;
using System.Windows.Forms;
using HalconDotNet;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        // 摄像头句柄
        private HTuple AcqHandle;

        // 标志位，表示是否正在实时检测
        private bool isDetecting = false;

        // 定时器，用于实时捕获和检测
        private readonly Timer captureTimer;

        public Form1()
        {
            InitializeComponent();

            // 初始化定时器
            captureTimer = new Timer { Interval = 100 }; // 100ms
            captureTimer.Tick += CaptureTimer_Tick;
        }

        // 打开/关闭摄像头
        private void btnOpenCamera_Click(object sender, EventArgs e)
        {
            if (AcqHandle == null)
            {
                try
                {
                    // 打开摄像头
                    HOperatorSet.OpenFramegrabber("DirectShow", 1, 1, 0, 0, 0, 0, "default", 8, "rgb", -1, "false", "default", "[0]", 0, -1, out AcqHandle);
                    btnOpenCamera.Text = "关闭摄像头";
                    btnOpenCamera.BackColor = Color.Red;
                    lblStatus.Text = "摄像头已启动";

                    // 启动定时器，开始捕获图像
                    captureTimer.Start();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("无法打开摄像头: " + ex.Message);
                }
            }
            else
            {
                // 关闭摄像头
                HOperatorSet.CloseFramegrabber(AcqHandle);
                AcqHandle = null;
                btnOpenCamera.Text = "打开摄像头";
                btnOpenCamera.BackColor = Color.Green;
                lblStatus.Text = "摄像头已关闭";

                // 停止定时器
                captureTimer.Stop();
            }
        }

        // 开始/停止检测
        private void btnDetect_Click(object sender, EventArgs e)
        {
            if (isDetecting)
            {
                StopDetection();
            }
            else
            {
                StartDetection();
            }
        }

        // 开始检测
        private void StartDetection()
        {
            if (AcqHandle == null)
            {
                MessageBox.Show("请先打开摄像头");
                return;
            }

            isDetecting = true;
            btnDetect.Text = "停止检测";
            lblStatus.Text = "正在实时检测...";
        }

        // 停止检测
        private void StopDetection()
        {
            isDetecting = false;
            btnDetect.Text = "开始检测";
            lblStatus.Text = "检测已停止";
        }

        // 定时器触发的事件
        private void CaptureTimer_Tick(object sender, EventArgs e)
        {
            if (AcqHandle == null) return;

            try
            {
                // 捕获一帧图像
                HOperatorSet.GrabImage(out HObject currentImage, AcqHandle);

                // 显示图像
                hWindowControl1.HalconWindow.ClearWindow();
                hWindowControl1.HalconWindow.DispObj(currentImage);

                // 如果正在检测，则执行检测逻辑
                if (isDetecting)
                {
                    DetectObject(currentImage);
                }
            }
            catch (Exception ex)
            {
                lblStatus.Text = "捕获或检测失败: " + ex.Message;
                StopDetection();
            }
        }

        // 检测物体
        private void DetectObject(HObject image)
        {
            try
            {
                // 转换为灰度图像
                HOperatorSet.Rgb1ToGray(image, out HObject grayImage);

                // 二值化处理
                HOperatorSet.Threshold(grayImage, out HObject region, 0, 50);

                // 形态学操作，去除噪声
                HOperatorSet.ClosingCircle(region, out HObject regionClosing, 5.5);

                // 连接区域
                HOperatorSet.Connection(regionClosing, out HObject connectedRegions);

                // 选择最大的区域
                HOperatorSet.SelectShape(connectedRegions, out HObject selectedRegions, "area", "and", 5000, 100000);

                // 计算区域面积
                HOperatorSet.AreaCenter(selectedRegions, out HTuple area, out _, out _);

                // 判断是否可以检测到
                if (area.Length > 0 && area[0].D > 20000) // 面积大于 150000 像素
                {
                    lblDetect.Text = "检测到";
                    lblDetect.BackColor = Color.White;
                    hWindowControl1.HalconWindow.SetColor("red");
                    hWindowControl1.HalconWindow.DispObj(selectedRegions);
                }
                else
                {
                    // 未检测到物体时，清空显示并更新状态
                    lblDetect.Text = "没有检测到";
                    lblDetect.BackColor = Color.Red;
                    hWindowControl1.HalconWindow.SetColor("black"); // 清空显示
                }
            }
            catch (Exception ex)
            {
                lblDetect.Text = "检测失败: " + ex.Message;
                lblDetect.BackColor = Color.Red;
            }
        }

        // 窗体关闭时释放资源
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (AcqHandle != null)
            {
                HOperatorSet.CloseFramegrabber(AcqHandle);
            }
        }
    }
}